﻿using Dting_libraries;
using EasyModbus;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static User_manage.User_Lgon;

namespace Station_interface
{
    public partial class Equipment3 : UserControl
    {        
        //开始时间
        public DateTime start_time;

        //PLC类属性
        public _PlcClass Station = new _PlcClass();

        //权限
        public static H_Level User_Level;

        //心跳变量
        private bool Heartbeat = false;


        //报警信息添加事件
        public delegate void AlarmAdd_Click(object sender);
        public event AlarmAdd_Click _AlarmAdd_Click;

        //报警信息指定删除事件
        public delegate void Alarmdelete_Click(object sender);
        public event Alarmdelete_Click _Alarmdelete_Click;

        //不良产品记录事件
        public delegate void ProductNG_Click(object sender);
        public event ProductNG_Click _ProductNG_Click;
        object ProductNG_lock = new object();

        //权限显示事件
        public delegate void Counterpoise_Click(object sender);
        public event Counterpoise_Click _Counterpoise_Click;

        //条码生产状态显示事件
        public delegate void BARstate_Click(object sender);
        public event BARstate_Click _BARstate_Click;

        //log打印事件
        public delegate void logs_Click(object sender);
        public event logs_Click _logs_Click;

        //
        ini_Class _ini_Class = new ini_Class("Config\\sys_data.ini");

        private string Quantity = string.Empty;//总产量
        private string OK_quantity = string.Empty;//OK数量
        private string NG_quantity = string.Empty;//NG数量
        private string Cycle = string.Empty;//CT/节拍
        private string Bar_sn = string.Empty;//生产条码

        private DataTable Infobuf; //运行信息
        private int logs_a = 0;
        private int logs_b = 0;
        private int logs_c = 0;
        private int timer_count = 0;
        private int[] EVAL = new int[300];
        private string[] EVAL_datatadel = new string[300];
        private int[] EVAL_info = new int[300];
        private DateTime wait_coun;
        private int wait_sn = 0;

        public class _PlcClass
        {
            public bool _IsConnected;
            public string _PlcName;
            public string _PlcIP;
            public ModbusClient _PLC;
            public byte[] Alarm_byte;           //报警信息寄存器
            public byte[] RunInfo_byte;           //运行信息寄存器
            public DataTable inAlarm_DataTable;    //报警信息寄存器
            public DataTable outAlarm_DataTable;   //报警信息寄存器

            public bool device_isNormal;//设备状态
            public bool device_isWait;  //设备状态
        }
        public Equipment3()
        {
            InitializeComponent();

            SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true);
            UpdateStyles();

        }

        public Equipment3(string Station_name="P1", string IP = "192.168.0.1")
        {
            InitializeComponent();
            SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, value: true);
            UpdateStyles();


            //label2.Text = Station_name;
            //label_IP.Text = IP;
            Station._PlcName = Station_name;
            Station._PlcIP = IP;
            //开始连接设备

            Task plc_task = new Task(() =>
            {
                _ConnectPlc();
                Thread.Sleep(10);
            });
            plc_task.Start();

            //初始化EVAL数组
            for (int i = 0; i < EVAL.Length; i++)
            {
                EVAL[i] = 0;
                EVAL_info[i] = 0;
            }

            //获取运行信息
            Infobuf = Deserialize<DataTable>(Application.StartupPath + "\\Config\\" + Station._PlcName + "_Info.config");

            //初始化报警列表
            Station.outAlarm_DataTable = new DataTable();
            for (int count = 0; count < 4; count++)
            {
                DataColumn dc = new DataColumn();
                Station.outAlarm_DataTable.Columns.Add(dc);
            }

            //连接数据库 只初始化一次
            if (Station._PlcName == "P1_工位")
            {
                //Task.Run(() => { MySQL_ini(); });
            }


            //开始处理逻辑线程任务
            Task _task = new Task(task_work);
            Task _task2 = new Task(task_work2);
            _task.Start();
            _task2.Start();
        }


        public CancellationTokenSource source = new CancellationTokenSource();

        //与设备交互
        private void task_work()
        {
            while (!source.IsCancellationRequested)
            {
                try
                {

                }
                catch (Exception er)
                {
                    ;
                }
            }
        }

        //与PLC交互
        private void task_work2()
        {
            while (!source.IsCancellationRequested)
            {
                try
                {

                }
                catch (Exception er)
                {
                    ;
                }
            }
        }

        #region //
        //
        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }
        //连接plc
        public int _ConnectPlc()
        {
            string messtrNG = "工位:" + Station._PlcName + ",IP:" + Station._PlcIP + " 连接异常，或未找到指定设备";
            string messtrOK = "工位:" + Station._PlcName + ",IP:" + Station._PlcIP + " 连接成功。。。";
            try
            {
                if (IP_ping(station_Interface1.label_IP.Text) == 0)
                {
                    _logs_Click?.Invoke(messtrNG);
                    Station._IsConnected = false;
                    return 2;
                }
                //判断是否已经连接过，如果有连接过将会断开重连
                if (Station._PLC != null)
                {
                    Station._PLC.Disconnect();
                    Station._PLC = null;
                    Station._IsConnected = false;
                }
                Station._PLC = new  ModbusClient(station_Interface1.label_IP.Text, 102);
                Station._PLC.ConnectionTimeout = 1000;
                if (Station._PLC != null)
                {
                    Station._PLC.Connect();
                    Station._IsConnected = Station._PLC.Connected;
                    _logs_Click?.Invoke(messtrOK);
                }
                else
                {
                    Station._IsConnected = false;
                    _logs_Click?.Invoke(messtrNG);
                    return 1;
                }
            }
            catch
            {
                _logs_Click?.Invoke(messtrNG);
                Station._PLC = null;
                Station._IsConnected = false;
                return 2;
            }

            return 0;
        }

        //断开plc
        public int _ClosePlc()
        {
            string messtrNG = "工位:" + Station._PlcName + ",IP:" + Station._PlcIP + " 断开异常。";
            string messtrOK = "工位:" + Station._PlcName + ",IP:" + Station._PlcIP + " 断开成功。。。";
            try
            {
                if (Station._PLC != null)
                {
                    Station._PLC.Disconnect();
                    Station._PLC = null;
                    Station._IsConnected = false;
                    _logs_Click?.Invoke(messtrOK);
                }
                else
                {
                    Station._IsConnected = false;
                    _logs_Click?.Invoke(messtrNG);
                    return 1;
                }
            }
            catch { _logs_Click?.Invoke(messtrNG); Station._IsConnected = false; return 2; }

            return 0;
        }

        //ping网络
        public int IP_ping(string ip)
        {
            ip = ip.Trim();
            if (ip == string.Empty)
                return 0;

            try
            {
                // 是否 Ping 的通 
                string bufstr = "ping test data";
                PingReply reply = new Ping().Send(ip, 150, Encoding.ASCII.GetBytes(bufstr));
                if (reply.Status == IPStatus.Success)
                {
                    return 1;
                }
                else
                    return 0;
            }
            catch (Exception er)
            {
                return 0;
            }

        }

        #endregion





    }
}
